#food.py
import os
import io
from urllib.request import urlopen
from alibabacloud_imagerecog20190930.client import Client
from alibabacloud_imagerecog20190930.models import RecognizeFoodAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import cv2
import threading
cam_lock = threading.Lock()
RecognizeFoodAdvanceRequest




config = Config(
  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
  # 访问的域名
  endpoint='imagerecog.cn-shanghai.aliyuncs.com',
  # 访问的域名对应的region
  region_id='cn-shanghai'
)

# 指定摄像头设备路径
device_path = '/dev/video21'



def aili_food():
  img = open(r'/userdata/main/img/food.jpg', 'rb')
  recognize_food_request = RecognizeFoodAdvanceRequest()
  recognize_food_request.image_urlobject = img
  runtime = RuntimeOptions()
  try:
    # 初始化Client
    client = Client(config)
    response = client.recognize_food_advance(recognize_food_request, runtime)
    # 获取整体结果
    food = response.body.to_map()['Data']['TopFives'][0]['Category']
    print (food)
    return food
  except Exception as error:
    print('获取失败 请回到food.py')
    return '获取失败 请回到food.py'

# 获取照片函数
def cap_read():
    # 确保img目录存在（不存在则创建）
    img_dir = 'img'
    if not os.path.exists(img_dir):
        os.makedirs(img_dir)
        print(f"创建目录: {img_dir}")

    # 创建VideoCapture对象
    cap = cv2.VideoCapture(device_path)  

    if not cap.isOpened():
        print(f"无法打开设备")
    else:
        print("成功打开摄像头")
    
    ret, frame = cap.read()

    if not ret:
        print("无法接收帧（可能是结束）")
    else:
        # 保存帧到img文件夹 - 使用相对路径
        save_path = os.path.join(img_dir, 'food.jpg')
        cv2.imwrite(save_path, frame)
        print(f"帧已保存为 {save_path}")

    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

